<template>
  <div class="top-nav">
    <div class="left-menu">
      <!-- 折叠按钮 -->
      <el-icon class="collapse-icon" @click="toggleCollapse">
        <component :is="isCollapse ? 'Expand' : 'Fold'" />
      </el-icon>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator=">">
        <el-breadcrumb-item>当前</el-breadcrumb-item>
        <el-breadcrumb-item v-for="(item, idx) in breadcrumbs" :key="item.path || idx">
          {{ item.meta.title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="right-menu">
      <!-- 用户信息下拉菜单 -->
      <el-dropdown @command="handleCommand">
        <span class="el-dropdown-link">
          <el-avatar :size="30" :icon="UserFilled" class="user-avatar" />
          <span class="username">{{ loginStore.username || 'Admin' }}</span>
          <el-icon class="el-icon--right"><arrow-down /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">个人中心</el-dropdown-item>
            <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useLoginStore } from '@/stores/loginStore';
import { UserFilled } from '@element-plus/icons-vue';

const props = defineProps({
  isCollapse: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['toggle-collapse']);

const route = useRoute();
const router = useRouter();
const loginStore = useLoginStore();

// 切换侧边栏折叠
const toggleCollapse = () => {
  emit('toggle-collapse');
};

// 计算面包屑导航
const breadcrumbs = computed(() => {
  // 过滤掉没有meta或title的项
  return route.matched.filter(item => item.meta && item.meta.title);
});

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    // 清除登录信息
    loginStore.clearLoginInfo();
    // 跳转到登录页
    router.push('/login');
  } else if (command === 'profile') {
    // 跳转到个人中心页
    router.push('/userCenter');
  }
};
</script>

<style scoped>
.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.left-menu {
  display: flex;
  align-items: center;
}

.collapse-icon {
  font-size: 22px;
  cursor: pointer;
  margin-right: 20px;
}

.right-menu {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 8px;
}

.username {
  font-size: 14px;
}
</style>